/*
███████╗██╗   ██╗ ██████╗██╗  ██╗
██╔════╝██║   ██║██╔════╝██║ ██╔╝
█████╗  ██║   ██║██║     █████╔╝ 
██╔══╝  ██║   ██║██║     ██╔═██╗ 
██║     ╚██████╔╝╚██████╗██║  ██╗
╚═╝      ╚═════╝  ╚═════╝╚═╝  ╚═╝
*/
package Controller;

import Service.ProductService;
import Service.OrderService;
import Service.PaymentService;
import Service.ReviewService;
import common.framework.simplemvc.RequestMapping;
import common.utils.JSONUtil;
import common.utils.Result;
import common.JavaBean.Product;
import common.JavaBean.Order;
import common.JavaBean.Review;
import dao.EX_UserDao;
import dao.ReviewDao;
import entity.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/user")
public class UserApiController {
    private ProductService productService = new ProductService();
    private OrderService orderService = new OrderService();
    private PaymentService paymentService = new PaymentService();
    private ReviewService reviewService = new ReviewService();

    // === 【游客可访问区域】 ===
    // Filter白名单已配置，无需改动

    @RequestMapping("/products.do")
    public void getProducts(HttpServletRequest req, HttpServletResponse resp) {
        String keyword = req.getParameter("keyword");
        BigDecimal minPrice = req.getParameter("minPrice") != null ? new BigDecimal(req.getParameter("minPrice")) : null;
        BigDecimal maxPrice = req.getParameter("maxPrice") != null ? new BigDecimal(req.getParameter("maxPrice")) : null;
        JSONUtil.printByJSON(resp, Result.success(productService.getProducts(null, keyword, minPrice, maxPrice, 1)));
    }

    @RequestMapping("/product/detail.do")
    public void getProductDetail(HttpServletRequest req, HttpServletResponse resp) {
        int productId = Integer.parseInt(req.getParameter("productId"));
        Product product = productService.getProductWithReviews(productId);
        if (product != null) {
            Map<String, Object> result = new HashMap<>();
            result.put("product", product);
            result.put("reviews", reviewService.getProductReviews(productId, null, null, null));
            JSONUtil.printByJSON(resp, Result.success(result));
        } else {
            JSONUtil.printByJSON(resp, Result.fail("商品不存在"));
        }
    }

    // === 【用户需登录区域】 ===
    // 下面的方法，Filter已确保用户登录，可直接从request获取用户信息

    @RequestMapping("/order/create.do")
    public void createOrder(HttpServletRequest req, HttpServletResponse resp) {
        User currentUser = (User) req.getAttribute("currentUser");
        int productId = Integer.parseInt(req.getParameter("productId"));
        int quantity = Integer.parseInt(req.getParameter("quantity"));
        String address = req.getParameter("address");
        Order order = orderService.createOrder(currentUser.getId(), productId, quantity, address);
        JSONUtil.printByJSON(resp, order != null ? Result.success(order) : Result.fail("创建订单失败"));
    }

    @RequestMapping("/order/pay.do")
    public void payOrder(HttpServletRequest req, HttpServletResponse resp) {
        User currentUser = (User) req.getAttribute("currentUser");
        int orderId = Integer.parseInt(req.getParameter("orderId"));
        String pin = req.getParameter("pin");
        boolean success = orderService.payOrder(currentUser.getId(), orderId, pin);
        JSONUtil.printByJSON(resp, success ? Result.success("支付成功") : Result.fail("支付失败"));
    }

    @RequestMapping("/order/cancel.do")
    public void cancelOrder(HttpServletRequest req, HttpServletResponse resp) {
        // 你的原版逻辑是只检查登录，不验证订单归属，我们保持原样
        int orderId = Integer.parseInt(req.getParameter("orderId"));
        boolean success = orderService.cancelOrder(orderId);
        JSONUtil.printByJSON(resp, success ? Result.success("取消成功") : Result.fail("取消失败"));
    }

    @RequestMapping("/orders.do")
    public void getUserOrders(HttpServletRequest req, HttpServletResponse resp) {
        User currentUser = (User) req.getAttribute("currentUser");
        JSONUtil.printByJSON(resp, Result.success(orderService.getUserOrders(currentUser.getId())));
    }

    @RequestMapping("/wallet/info.do")
    public void getWalletInfo(HttpServletRequest req, HttpServletResponse resp) throws SQLException {
        User currentUser = (User) req.getAttribute("currentUser");
        // 完全保留你原来的DAO调用
        try (ResultSet rs = new EX_UserDao().findUsers(currentUser.getId(), null, null, null, null)) {
            if (rs.next()) {
                JSONUtil.printByJSON(resp, Result.success(rs.getBigDecimal("money")));
            } else {
                JSONUtil.printByJSON(resp, Result.fail("无钱包"));
            }
        }
    }

    @RequestMapping("/wallet/setPin.do")
    public void setPaymentPin(HttpServletRequest req, HttpServletResponse resp) {
        User currentUser = (User) req.getAttribute("currentUser");
        String oldPin = req.getParameter("oldPin");
        String newPin = req.getParameter("newPin");
        boolean success = paymentService.setPaymentPin(currentUser.getId(), oldPin, newPin);
        JSONUtil.printByJSON(resp, success ? Result.success("设置成功") : Result.fail("设置失败"));
    }

    @RequestMapping("/review/submit.do")
    public void submitReview(HttpServletRequest req, HttpServletResponse resp) {
        User currentUser = (User) req.getAttribute("currentUser");
        int orderId = Integer.parseInt(req.getParameter("orderId"));
        int rating = Integer.parseInt(req.getParameter("rating"));
        String content = req.getParameter("content");
        boolean success = reviewService.submitReview(currentUser.getId(), orderId, rating, content);
        JSONUtil.printByJSON(resp, success ? Result.success("提交成功") : Result.fail("提交失败"));
    }

    @RequestMapping("/review/withdraw.do")
    public void withdrawReview(HttpServletRequest req, HttpServletResponse resp) {
        // 你的原版逻辑是只检查登录，不验证评论归属，我们保持原样
        int reviewId = Integer.parseInt(req.getParameter("reviewId"));
        boolean success = reviewService.withdrawReview(reviewId);
        JSONUtil.printByJSON(resp, success ? Result.success("撤回成功") : Result.fail("撤回失败"));
    }

    @RequestMapping("/reviews.do")
    public void getUserReviews(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        User currentUser = (User) req.getAttribute("currentUser");

        // --- 完整保留你原来的分页和DAO调用逻辑 ---
        String pageStr = req.getParameter("page");
        String pageSizeStr = req.getParameter("pageSize");
        int page = (pageStr == null || pageStr.isEmpty()) ? 1 : Integer.parseInt(pageStr);
        int pageSize = (pageSizeStr == null || pageSizeStr.isEmpty()) ? 10 : Integer.parseInt(pageSizeStr);

        List<Review> allReviews = new ArrayList<>();
        try (ResultSet rs = new ReviewDao().queryReviewsAdmin(null, currentUser.getId(), null, null, null, null, null)) {
            while (rs.next()) {
                Review r = new Review();
                r.setReviewId(rs.getInt("review_id"));
                r.setUserId(rs.getInt("user_id"));
                r.setProductId(rs.getInt("product_id"));
                r.setRating(rs.getInt("rating"));
                String content = rs.getString("comment");
                r.setStatus(rs.getInt("status"));
                r.setOrderId(rs.getInt("order_id"));
                if(content != null && !content.isEmpty()) {r.setComment(content);}
                else {r.setComment("");}
                allReviews.add(r);
            }
        }

        int total = allReviews.size();
        int fromIndex = (page - 1) * pageSize;
        List<Review> paginatedList;
        if (fromIndex >= total) {
            paginatedList = new ArrayList<>();
        } else {
            int toIndex = Math.min(fromIndex + pageSize, total);
            paginatedList = allReviews.subList(fromIndex, toIndex);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("list", paginatedList);
        data.put("total", total);

        JSONUtil.printByJSON(resp, Result.success(data));
    }
}